<?php

namespace app\api\controller;

use app\admin\model\giy\Evaluate;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;
use app\admin\model\user\Address;
use function Sodium\add;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third', 'createPoster','getUserPhone','wxLogin'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @param string $account 账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email 邮箱
     * @param string $mobile 手机号
     * @param string $code 验证码
     */
    public function register()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $pwd = $this->request->post('pwd');
        $mobile = $this->request->post('mobile');
        /*$code = $this->request->post('code');*/
        $invite_code = $this->request->post('invite_code');
        $openid = $this->request->post('openid');
        $session_key = $this->request->post('session_key');
        $tjUser = Db::name('user')->where(['invite_code' => $invite_code])->find();
        if (!$username || !$password || !$openid || !$session_key) {
            $this->error(__('Invalid parameters'));
        }
        if ($pwd != $password) {
            $this->error(__('Two passwords do not match'));
        }
//        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
//            $this->error(__('Mobile is incorrect'));
//        }
//        $ret = Sms::check($mobile, $code, 'register');
//        if (!$ret) {
//            $this->error(__('Captcha is incorrect'));
//        }
        if (!$tjUser) {
            $this->error(__('Incorrect invitation code'));
        }
        $ret = $this->auth->register($username, $password, '', $mobile, ['pid' => $tjUser['id'], 'openid' => $openid, 'session_key' => $session_key]);
        if ($ret) {
            Db::name('user')->where(['id' => $tjUser['id']])->setInc('referrals');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            addTotalPeople($tjUser['id']);
            $this->success(__('Sign up successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    public function getUserPhone()
    {
        $code = $this->request->param('code', '');
        $appid = 'wx3216a1dfd52d5f00';
        $app_secret = '5dad85a5ad9e31b3035db6c79dccb0c2';
        if (!$code) $this->error(__('The required parameter is missing'));
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$app_secret}&js_code={$code}&grant_type=authorization_code";
        $response = file_get_contents($url);
        $decryptSession = json_decode($response, true);
        $sessionKey = $decryptSession['session_key'];
        $openid = $decryptSession['openid'];
        $params = [
            'iv' => $this->request->param('iv'),
            'encryptedData' =>$this->request->param('encryptedData')
        ];
        extract($params);
        if (empty($iv) || empty($sessionKey) || empty($encryptedData)) {
            $this->error('缺少必要参数!');
        }
        $errCode = $this->decryptData($appid, $sessionKey, $encryptedData, $iv, $data);
        if ($errCode == 0) {
            $res = [];
            $res['openid'] = $openid;
            $res['session_key'] = $sessionKey;
            $res['mobile'] = $data->phoneNumber;
            $this->success(__('Operation completed'), $res);
        } else {
            $this->error(__('Operation failed'));
        }
    }

    private function decryptData($appid, $sessionKey, $encryptedData, $iv, &$data)
    {
        if (strlen($sessionKey) != 24) {
            return -41001;
        }
        $aesKey = base64_decode($sessionKey);


        if (strlen($iv) != 24) {
            return -41002;
        }
        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt($aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);
        if ($dataObj == NULL) {
            return -41003;
        }
        if ($dataObj->watermark->appid != $appid) {
            return -41004;
        }
        $data = $dataObj;
        return 0;
    }

    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio 个人简介
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $mobile = $this->request->post('mobile');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        if($mobile){
            $exists = \app\common\model\User::where('mobile', $mobile)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('mobile already exists'));
            }
            $user->mobile = $mobile;
        }
        $user->avatar = $avatar;
        $user->save();
        $this->success(__('Operation completed'));
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @param string $email 邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @param string $platform 平台名称
     * @param string $code Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo' => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @param string $mobile 手机号
     * @param string $newpassword 新密码
     * @param string $captcha 验证码
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $pwd = $this->request->post("pwd");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if ($pwd != $newpassword) {
            $this->error(__('Two passwords do not match'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }

    //新增收货地址
    public function addAddress()
    {
        $user = $this->auth->getUserinfo();
        $recipient_name = $this->request->param('recipient_name', '', 'trim,htmlspecialchars');
        $phone_number = $this->request->param('phone_number', '', 'trim,htmlspecialchars');
        $address_line = $this->request->param('address_line', '', 'trim,htmlspecialchars');
        $province = $this->request->param('province', '', 'trim,htmlspecialchars');
        $city = $this->request->param('city', '', 'trim,htmlspecialchars');
        $area = $this->request->param('area', '', 'trim,htmlspecialchars');
        $is_default = $this->request->param('is_default', 0, 'trim,htmlspecialchars');
        $model = new Address();
        if (!$recipient_name || !$phone_number || !$address_line || !$province || !$city || !$area) {
            $this->error(__('Invalid parameters'));
        }

        $data = array(
            'user_id' => $user['id'],
            'recipient_name' => $recipient_name,
            'phone_number' => $phone_number,
            'address_line' => $address_line,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'is_default' => $is_default,
            'create_time' => time()
        );
        Db::startTrans();
        try {
            if ($is_default == 1) {
                $where = [];
                $where['user_id'] = $user['id'];
                $where['is_default'] = 1;
                Db::name('user_address')->where($where)->update(['is_default' => 0]);
            }
            $address_id = $model->insertGetId($data);
            if ($address_id) {
                Db::commit();
                $this->success(__('Operation completed'));
            }

        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());

        }
    }

    public function editAddress()
    {
        $user = $this->auth->getUserinfo();
        $recipient_name = $this->request->param('recipient_name', '', 'trim,htmlspecialchars');
        $phone_number = $this->request->param('phone_number', '', 'trim,htmlspecialchars');
        $address_line = $this->request->param('address_line', '', 'trim,htmlspecialchars');
        $province = $this->request->param('province', '', 'trim,htmlspecialchars');
        $city = $this->request->param('city', '', 'trim,htmlspecialchars');
        $area = $this->request->param('area', '', 'trim,htmlspecialchars');
        $is_default = $this->request->param('is_default', 0, 'trim,htmlspecialchars');
        $address_id = $this->request->param('address_id', '', 'trim,htmlspecialchars');
        $model = new Address();
        $data = array(
            'user_id' => $user['id'],
            'recipient_name' => $recipient_name,
            'phone_number' => $phone_number,
            'address_line' => $address_line,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'is_default' => $is_default,
            'updatetime' => time()
        );
        Db::startTrans();
        try {
            if ($is_default == 1) {
                $where = [];
                $where['user_id'] = $user['id'];
                $where['is_default'] = 1;
                Db::name('user_address')->where($where)->update(['is_default' => 0]);
            }
            $address_id = Db::name('user_address')->where('address_id', $address_id)->update($data);
            if ($address_id) {
                Db::commit();
                $this->success(__('Operation completed'));
            }

        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());

        }
    }

    //删除收货地址
    public function delAddress()
    {
        $user = $this->auth->getUserinfo();
        $address_id = $this->request->param('address_id', '', 'trim,htmlspecialchars');
        $address_id = Db::name('user_address')->where('address_id', $address_id)->delete();
        if ($address_id) {
            $this->success(__('Operation completed'));
        } else {
            $this->error(__('Operation failed'));
        }
    }

    //地址列表
    public function addressList()
    {
        $user = $this->auth->getUserinfo();
        $is_default = $this->request->param('is_default');
        $where = [];
        $where['user_id'] = $user['id'];
        if ($is_default) {
            $where['is_default'] = $is_default;
        }
        $model = new Address();
        $list = $model->where($where)->order('create_time desc')->paginate()->each(function ($item) {
            $item['create_time'] = date("Y-m-d H:i:s", $item['create_time']);
            return $item;
        });
        $this->success(__('Operation completed'), $list);
    }

    //最新个人信息
    public function getUserInfo()
    {
        $userinfo = $this->auth->getUserinfo();
        $user_id = $userinfo['id'];
        $info = Db::name('user')
            ->field('id,username,avatar,invite_code,qrcode,score,level,is_partner,mobile')
            ->where('id', $user_id)
            ->find();
        $info['avatar'] = cdnurl($info['avatar'], true);
        $url = cdnurl("/h5/#/pages/index/register?inviter=" . $info['invite_code'], true);
        $info['invite_url'] = $url;
        /* if (!$info['qrcode']) {
             make_qrcode($user_id, $url);
             Db::name('user')
                 ->where('id', $user_id)
                 ->setField('qrcode', '/uploads/qrcode/' . $user_id . '.png');
             $info['qrcode'] = cdnurl('/uploads/qrcode/' . $user_id . '.png', true);
         } else {
             $info['qrcode'] = cdnurl($info['qrcode'], true);
         }*/
        $this->success('ok', $info);
    }

    /**
     * 获取团队信息
     * */
    public function team()
    {
        $pid = $this->request->post('pid/d', 0);
        if ($pid > 0) {
            $info = Db::name('user')->where(['id' => $pid])->field('id,level,total_invest,total_people,referrals,username')->find();
            $list = Db::name('user')->where(['pid' => $pid])->field('id,level,total_invest,total_people,referrals,username')->select();
        } else {
            $user = $this->auth->getUserinfo();
            $info = Db::name('user')->
            field('id,level,total_invest,total_people,referrals,username')
                ->where('id', $user['id'])
                ->find();
            $list = Db::name('user')->where(['pid' => $user['id']])->field('id,level,total_invest,total_people,referrals,username')->select();
        }
        $data = array(
            'info' => $info,
            'list' => $list
        );
        $this->success('OK', $data);
    }

    /**
     * 提现
     * */
    public function withdraw()
    {
        $user_info = $this->auth->getUserinfo();
        $user_id = $user_info['id'];
        $user_info = Db::name('user')->where('id', $user_id)->find();
        $key = "withdraw_" . $user_id;
        if (cache($key)) {
            $this->error(__('System Busy'));
        }
        cache($key, 1, 3);
        $number = $this->request->param('number');
        $bank_name = $this->request->param('bank_name');
        $user_name = $this->request->param('user_name');
        $bank_number = $this->request->param('bank_number');
        if (!is_numeric($number) || $number <= 0) {
            $this->error(__("Invalid parameters"));
        }
        Db::startTrans();
        try {
            //余额判断
            if ($user_info['score'] < $number) throw new Exception("Insufficient balance");
            $scole = config('site.handling_charge');
            $bl = (100 - $scole) / 100;
            $result = bcmul($number, $bl, 2);
            $dec = Db::name('user')->where('id', $user_id)->setDec('score', $number);
            if (!$dec) throw new Exception("System Error");
            $insert = [
                'user_id' => $user_id,
                'number' => $number,
                'result' => $result,
                'charge' => bcsub($number, $result, 2),
                'memo' => '提现',
                'create_time' => time(),
                'update_time' => time(),
                'status' => 0,
                'bank_name' => $bank_name,
                'user_name' => $user_name,
                'bank_number' => $bank_number,

            ];
            Db::name('withdraw')->insert($insert);
            add_score_log($user_id, -$number, $user_info['score'], bcsub($user_info['score'], $number, 2), '提现', "2");
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error(__($e->getMessage()));
        }
        $this->success(__("Operation completed"));
    }

    /**
     * 提现记录
     * */
    public function withdrawLog()
    {
        $lang = $this->request->langset();
        if ($lang == 'en') {
            $status_list = [
                '0' => 'Pending',
                '1' => 'Approved',
                '2' => 'Reject'
            ];
        } else {
            $status_list = [
                '0' => '待处理',
                '1' => '已到账',
                '2' => '已驳回'
            ];
        }

        $user_info = $this->auth->getUserinfo();
        $user_id = $user_info['id'];
        $where['user_id'] = $user_id;
        $list = Db::name('withdraw')
            ->field('id,number,result,create_time,status,bank_name,user_name,bank_number')
            ->where($where)
            ->order('id DESC')
            ->paginate()->each(function ($item) use ($status_list) {
                $item['create_time'] = date('Y-m-d H:i:s', $item['create_time']);
                $item['status_text'] = __($status_list[$item['status']]);
                return $item;
            });
        $this->success(__('Operation completed'), $list);
    }

    //积分明细
    public function getScoreLog()
    {
        $user = $this->auth->getUserinfo();
        $state = $this->request->param('type');
        $where = [];
        $where['user_id'] = $user['id'];
        if ($state) {
            $where['type'] = $state;
        }
        $list = Db::name('user_score_log')->where($where)->order('createtime desc')
            ->paginate()->each(function ($item) {
                $item['createtime'] = date("Y-m-d H:i:s", $item['createtime']);
                return $item;
            });
        $this->success(__('Operation completed'), $list);
    }

    //新增评价
    public function addEvaluate()
    {
        $user = $this->auth->getUserinfo();
        $goods_id = $this->request->param('goods_id');
        $content = $this->request->param('content');
        $where = [];
        $where['user_id'] = $user['id'];
        $where['goods_id'] = $goods_id;
        $model = new Evaluate();
        $info = $model->where($where)->find();
        if ($info) {
            $this->error('Cannot repeat comments');
        }
        Db::startTrans();
        try {
            $data = array(
                'user_id' => $user['id'],
                'goods_id' => $goods_id,
                'content' => $content,
                'createtime' => time()
            );
            $model->insertGetId($data);
            $score = config('site.evaluate_score');
            if ($score) {
                $rs = Db::name('user')->where('id', $user['id'])->setInc('score', $score);
                if (!$rs) {
                    throw new Exception("Operation failed");
                }
                add_score_log($user['id'], $score, $user['score'], bcadd($user['score'], $score, 2), '评价返现', '1');
            }
            Db::commit();
            $this->success(__('Operation completed'));
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    //邀请海报
    public function qrcodeWx()
    {
        $user = $this->auth->getUserinfo();
        $info = Db::name('user')->where('id', $user['id'])->find();
        if ($info['qrcode']) {
            $info['qrcode'] = cdnurl($info['qrcode'], true);
            $this->success(__('Operation completed'), $info['qrcode']);
        } else {
            $patch2 = './uploads/poster/' . $user['id'] . '.png';//相对路径
            $page = "pages/index/index";//路径
            $appid = 'wx3216a1dfd52d5f00';
            $app_secret = '5dad85a5ad9e31b3035db6c79dccb0c2';
            $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' . $appid . '&secret=' . $app_secret;
            $data = $this->getCurlWxapp($url);
            $data = json_decode($data, true);
            $postdata['scene'] = $user['invite_code'];
            $postdata['width'] = 600;
            $postdata['page'] = $page;
            $postdata['auto_color'] = false;
            $postdata['line_color'] = array('r' => '0', 'g' => '0', 'b' => '0');
            $postdata['is_hyaline'] = false;
            $post_data = json_encode($postdata);
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $data['access_token'];
            $result = $this->postCurlWxapp($url, $post_data);
            //$patch = cdnurl($patch2, true);
            file_put_contents($patch2, $result);
            $return = $patch2;//路径
            $posterPath = './uploads/poster/' . 'user' . '_' . $user['invite_code'] . '.png';
            $posterPath1 = '/uploads/poster/' . 'user' . '_' . $user['invite_code'] . '.png';
            $image = $this->createPoster($patch2, $posterPath);
            if ($image) {
                $id = Db::name('user')->where('id', $user['id'])->update(['qrcode' => $posterPath1]);
                if ($id) {
                    $this->success(__('Operation completed'), cdnurl($posterPath1, true));
                } else {
                    $this->error(__('Operation failed'));
                }
            }
        }
    }

    function createPoster($qrCodeData, $posterPath)
    {
        // 加载背景图
        $qrCodeData = file_get_contents($qrCodeData);
        $backgroundPath = './uploads/poster/background.jpeg';
        $background = imagecreatefromjpeg($backgroundPath); // 可以根据背景图格式调整
        $posterWidth = imagesx($background);
        $posterHeight = imagesy($background);
        // 创建海报
        $poster = imagecreatetruecolor($posterWidth, $posterHeight);
        imagecopy($poster, $background, 0, 0, 0, 0, $posterWidth, $posterHeight);
        // 添加二维码
        $qrCode = imagecreatefromstring($qrCodeData);
        $qrCodeWidth = imagesx($qrCode);
        $qrCodeHeight = imagesy($qrCode);
        $qrCodeX = ($posterWidth - $qrCodeWidth) / 2; // 居中
        $qrCodeY = $posterHeight - $qrCodeHeight - 120; // 距底部50px
        imagecopy($poster, $qrCode, $qrCodeX, $qrCodeY, 0, 0, $qrCodeWidth, $qrCodeHeight);
        /*  // 添加文本
          $textColor = imagecolorallocate($poster, 255, 255, 255); // 白色
          $fontPath = __DIR__ . '/path/to/font.ttf'; // 字体路径
          $text = "111111"; // 文本内容
          imagettftext($poster, 20, 0, 50, 50, $textColor, $fontPath, $text);*/

        // 保存海报
        imagepng($poster, $posterPath);
        imagedestroy($poster);
        imagedestroy($background);
        imagedestroy($qrCode);
        return true;
    }

//生成小程序海报get请求
    public function getCurlWxapp($url)
    {
        $info = curl_init();
        curl_setopt($info, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($info, CURLOPT_HEADER, 0);
        curl_setopt($info, CURLOPT_NOBODY, 0);
        curl_setopt($info, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($info, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($info, CURLOPT_URL, $url);
        $output = curl_exec($info);
        curl_close($info);
        return $output;
    }

    //生成小程序海报post请求
    public function postCurlWxapp($url, $data)
    {
        $ch = curl_init();
        $header[] = "Accept-Charset: utf-8";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            return false;
        } else {
            return $tmpInfo;
        }
    }

    //申请合伙人
    public function partner()
    {
        $user = $this->auth->getUserinfo();
        $info = Db::name('partner')->where('user_id', $user['id'])->find();
        if ($info) {
            $this->error(__('Duplicate application'));
        }
        $province = $this->request->post('province');
        $city = $this->request->post('city');
        $area = $this->request->post('area');
        $name = $this->request->post('name');
        $phone = $this->request->post('phone');
        $code = $this->request->post('code');
        if (!Sms::check($phone, $code, 'paetner')) {
            $this->error(__('Captcha is incorrect'));
        }
        $data = array(
            'user_id' => $user['id'],
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'name'=>$name,
            'phone'=>$phone,
            'createtime' => time()
        );
        $id=Db::name('partner')->insertGetId($data);
        if ($id) {
            $this->success(__('Operation completed'));
        } else {
            $this->error(__('Operation failed'));
        }
    }
    //合伙人申请记录
    public function partnerList(){
        $user = $this->auth->getUserinfo();
        $info = Db::name('partner')->where('user_id', $user['id'])->find();
        if ($info) {
            $info['createtime']=date("Y-m-d H:i:s", $info['createtime']);
        }else{
            $info=[];
        }
        $this->success(__('Operation completed'),$info);
    }
    public function wxLogin()
    {
        $appid = 'wx3216a1dfd52d5f00';
        $app_secret = '5dad85a5ad9e31b3035db6c79dccb0c2';
        $code = $this->request->param('code'); // 从小程序获取的授权码
        if (!$code) $this->error(__('The required parameter is missing'));
        $url="https://api.weixin.qq.com/cgi-bin/token?appid={$appid}&secret={$app_secret}&grant_type=client_credential";
        $res=file_get_contents($url);
        $res=json_decode($res, true);
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$app_secret}&js_code={$code}&grant_type=authorization_code";
        $response = file_get_contents($url);
        $decryptSession= json_decode($response, true);
        //$decryptSession = $wechat->code($code);
        if (!isset($decryptSession['session_key'])) {
            $this->error(__('Not acquired session_key'));
        }
        $res['openid'] = $decryptSession['openid'];
        $res['session_key'] = $decryptSession['session_key'];
        $this->success(__('Operation completed'), $res);
        /*$result = [];
        try {
            if (!$decryptSession || !isset($decryptSession['openid'])) {
                $this->error(__('Login failure'));
            }

            $user = \app\common\model\User::where('mp_openid', $decryptSession['openid'])->find();
            if (!empty($user)) {
                $result = $this->auth->direct($user['id']);
            } /*else {
                // 写入个人数据
                $userinfo = [
                    'mp_openid' => $decryptSession['openid'],
                    'nickName' => "用户" . substr(md5($decryptSession['openid']), 0, 6),
                    'avatarUrl' => "/uploads/default/avatar.png",
                    'gender' => "1",
                    'mp_session_key'=>$decryptSession['session_key']
                ];
                $result = $this->auth->wechatRegister($decryptSession['openid'], $userinfo, '');
            }
        } catch (\Exception $e) {
            $this->error($e->getMessage() . $e->getLine());
        }*/
       /* if ($result) {
            $userinfo = $this->auth->getUserInfo();
            $userinfo['avatar'] = cdnurl($userinfo['avatar'], true);
            $this->success(__('Operation completed'), $userinfo);
        } else {
            $this->error(__('Operation failed'));
        }*/
    }
}





